﻿using Microsoft.AspNetCore.Http;
using SD.TeachSystem.Common.LogTools;
using SD.TeachSystem.Common.Services;
using SD.TeachSystem.EntityFrameworkCore.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SD.TeachSystem.Common.Middleware
{
    public class ExceptionMiddleware
    {
        private readonly RequestDelegate _next;

        public ExceptionMiddleware(RequestDelegate next) 
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                // 捕获全局异常并记录日志
                await GlobalTools.WriteLog(
                    methodName: MethodBase.GetCurrentMethod().Name,
                    title: "Unhandled Exception",
                    logLevel: LogLevel.Error,
                    message: ex.ToString());

                //// 返回统一的错误响应
                //context.Response.ContentType = "application/json";
                //context.Response.StatusCode = StatusCodes.Status500InternalServerError;

                //var errorResponse = new
                //{
                //    StatusCode = 500,
                //    Message = "An unexpected error occurred."
                //};

                //await context.Response.WriteAsJsonAsync(errorResponse);
            }
        }
    }
}
